<%@ page contentType="text/html; charset=UTF-8"%>
<%@ include file="/jsp/common/common.jsp"%>
<html> 
    <head>
        <title><%=IConstant.PROGRAEM_TITLE%></title>
        
		<script language="javascript">
		
			var myNode;
		    var gridButton;
		    var storeGrid;
			var addDicWin;
			var tree;
			var addForm;
			
			Ext.onReady(function(){
		    	Ext.lib.Ajax.defaultPostHeader += '; charset=utf-8';
		    	
		    	treeBuild();
		    	
	            var layout = new Ext.Viewport({   
	                layout: 'border',   
	                margins:'5 0 5 5',   
	                items: [ { region: 'center',   
	                    //title: '角色管理',
	                    height:800,
	                    layout:'fit',
	                    items:[tree]  
	                }]   
	            }); 

		    }); 
		    
			var treeBuild = function () {
                
				/* 生成Ttee,放到tree Div里面 */
	        	tree = new Ext.tree.TreePanel({
	        			root: new Ext.tree.AsyncTreeNode({   
	                		id : "0", 
	                		draggable:false, 
	                		singleClickExpand:true, 
	                		text : "<%=IConstant.PROGRAEM_TITLE%>"
	 					}),
	 					loader:new Ext.tree.TreeLoader({
	                    	url : 'menu!getMenu.do?parentID=',
	                    	listeners:{"beforeload":function(loader, node){ 
	            						loader.url ='menu!getMenu.do?parentID=' + node.id ;
	                    			}}
	               		 	}),
	                    id:"mytree",    
				        useArrows:true,
				        autoScroll:true,
				        animate:true,
				        enableDD:true,
				        //height:800,
						tbar : [ {
							id :'addDicButton',
							text :'增加',
				            cls:'x-btn-text-icon',
				            icon:'<%=contextPath%>/images/add.gif',
							tooltip :'添加一个应用',
							handler:addButtonClick,
							hidden:<%=session.getAttribute("btn_add_display") != null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>
						}, '-', {
							id :'updateDicButton',
							text :'修改',
				            cls:'x-btn-text-icon',
				            icon:'<%=contextPath%>/images/edit.gif',
							tooltip :'修改所选应用',
							handler:updateButtonClick,
							hidden:<%=session.getAttribute("btn_query_display") != null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>
						}, '-', {
							id :'deleteDicButton',
							text :'删除',
				            cls:'x-btn-text-icon',
				            icon:'<%=contextPath%>/images/delete.gif',
							tooltip :'删除所选应用',
							handler:delButtonClick,
							hidden:<%=session.getAttribute("btn_delete_display") != null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>
						} ,'->',{
							id :'editDicButton',
							text :'修改2',
							hidden:true,
				            cls:'x-btn-text-icon',
				            icon:'<%=contextPath%>/images/delete.gif',
							tooltip :'删除所选应用',
							handler:editButtonClick
						} ],
				        containerScroll: true
				});
	         	
	            /* 单击 */     
	            tree.on("click",function(node) {
	            
	            	myNode = node;
	            	
				   if (node.isLeaf() == undefined || !node.isLeaf()){
	   
				        if (!node.isExpanded()) {
				           node.expand();		
				        } else {
				           node.collapse();
				        }              
				   }
				         
	            });
	            
	            /* 双击 */
	            tree.on("dblclick",function(node) {
	            	myNode = node;
	            	// 修改
	            	updateButtonClick();
				});
	            
	            /* Tree绑定菜单 */
				tree.on("contextmenu",function (node,e) {
				    myNode = node
	      			e.preventDefault();   
	        		memu.showAt(e.getXY());   
				});
	            
	            /* 右键事件 */
			    var memu = new Ext.menu.Menu({   
			        allowOtherMenus:true,   
			        items:[{   
			            text:'增加',
			            hidden:<%=session.getAttribute("btn_add_display") != null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>, 
			            handler:addButtonClick
			        },{   
			            text:'修改',
			            hidden:<%=session.getAttribute("btn_query_display") != null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>, 
			            handler:updateButtonClick
			        },{   
			            text:'删除',
			            hidden:<%=session.getAttribute("btn_delete_display") != null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>,
			            handler:delButtonClick  
			        }]   
			    }); 

			}  

			/***************** 按钮Grid  start ****************************************/
			var winBuild = function() {

				addForm = new Ext.FormPanel( {
					frame :true,
					region:'center',
					labelAlign :'right',
					waitMsgTarget :true,
					autoScroll :true,
					buttonAlign :'center',
					method :'POST',
					url :'menu!save.do',
					items : [ {
						xtype :'textfield',
						fieldLabel :'名称',
						name :'entity.title',
						allowBlank :false,
						maxLength :50,
						width :150,
						emptyText:'必须输入'
					}, {
						xtype :'textfield',
						fieldLabel :'提示',
						name :'entity.qtip',
						maxLength :50,
						width :250
					}, {
						xtype :'textfield',
						fieldLabel :'URL',
						name :'entity.url',
						maxLength :100,
						width :250
					}, {
						xtype :'textfield',
						fieldLabel :'描述',
						name :'entity.note',
						maxLength :50,
						width :250
					}, {
						xtype :'numberfield',
						fieldLabel :'排序',
						name :'entity.sortId',
						allowDecimals:false,
						maxLength :5,
						width :150,
						emptyText:'请输入整数',
						style:'text-align:right'
					}, {
						xtype :'hidden',
						name :'entity.id',
						value :'0'
					}, {
						xtype :'hidden',
						name :'entity.parentID',
						value :'0'
					},{
						xtype :'hidden',
						name :'buttonIds',
						value :'0'
					}]
				});

				var MyRecord = Ext.data.Record.create([
					{name:'id',type:'string'},
					{name:'iconCls',type:'string'},
					{name:'title',type:'string'},
					{name:'note',type:'string'}
				]);
		
				var cm = new Ext.grid.ColumnModel([
					{header :"编号",dataIndex :'id', hidden :true,editor:new Ext.grid.GridEditor(
						new Ext.form.Hidden({	
						}))},
					{header :"按钮编号",dataIndex :'iconCls',editor:new Ext.grid.GridEditor(
						new Ext.form.TextField({
							allowBlank:false,
							maxLength:20,
							maxLengthText:'按钮编号最大输入10个汉字或者20个字符'
						}))},
					{header :"按钮名称",dataIndex :'title',editor:new Ext.grid.GridEditor(
						new Ext.form.TextField({
							allowBlank:false,
							maxLength:20,
							maxLengthText:'按钮名称最大输入10个汉字或者20个字符'
						}))},		
					{header :"排序号",dataIndex :'sortId',editor:new Ext.grid.GridEditor(
						new Ext.form.NumberField({
							allowBlank:true,
							minValue:0,
							maxValue:99,							
							maxLengthText:'请输入两位数字'
						}))}	
				]);
			
				// 加载分页数据
				storeGrid = new Ext.data.Store({
					proxy :new Ext.data.HttpProxy({
						url:"menuList!getListExt.do"//?limit=10&start=0"// +'!list'
					}),
					baseParams : {limit:10},
					reader :new Ext.data.JsonReader({
						root :'result',
						totalProperty :'totalCount',
						fields : [ 'id', 'iconCls', 'title','sortId']
					})//,
					//autoLoad:true
				});
		
				// 创建GridPanel
				gridButton = new Ext.grid.EditorGridPanel({
					titleVisible:false,
					store :storeGrid,
					frame:true,
					height:'330',
		        	cm:cm,
		        	selModel:new Ext.grid.RowSelectionModel(),
					sm : new Ext.grid.CheckboxSelectionModel (),
					loadMask : {msg :'载入中,请稍候...'},
					viewConfig:{forceFit:true},
					tbar : [
					{   id :'1',
						text :'添加按钮',
		            	cls:'x-btn-text-icon',
		           	 	icon:'<%=contextPath%>/images/add.gif',
						tooltip :'添加按钮至当前应用',
				        hidden:<%=session.getAttribute("btn_addButton_display") != null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>, 
						handler:function() {
							if (addForm.getForm().findField("entity.id").getValue() == "0") {
								Ext.MessageBox.alert('提示', '请先保存基本信息！');
								return;
							}
							var p = new MyRecord({
								id:'',
								title:'',
								iconCls:'',
								url:''
							});
							gridButton.stopEditing();
							storeGrid.insert(0,p);
							gridButton.startEditing(0,0);
						}
					}, '-', {
						id :'2',
						text :'删除按钮',
				        hidden:<%=session.getAttribute("btn_deleteButton_display")!= null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>, 
		            	cls:'x-btn-text-icon',
		            	icon:'<%=contextPath%>/images/delete.gif',
						tooltip :'从当前应用中删除按钮',
						handler:function() {
							var records = gridButton.getSelectionModel().getSelections();
							if (records != null && records.length > 0) {
								deleteButton(records[0].data.id);
							} else {
								Ext.MessageBox.alert('提示 ', "请选择要删除的按钮！");
								return false;
							}
						}
					}],
					bbar :new Ext.PagingToolbar({
						id:'b',
						pageSize :10,
						store :storeGrid,
						displayInfo :true,
						displayMsg :'显示 {0} - {1} 共 {2} 条',
						emptyMsg :"没有数据显示！",
						beforePageText :"页码 ",
						afterPageText :"共 {0} 页",
						firstText :"首页",
						lastText :"末页",
						nextText :"下一页",
						prevText :"上一页",
						refreshText :"刷新"
					})
				});
		
				// 编辑后处理
				gridButton.on('afteredit',function(e){
					if (e.record.data.iconCls!="" && e.record.data.title != "" && e.record.data.sortId != "") {
					
						// 验证编号是否重复
						if (e.record.data.id == "" || e.record.data.id == "0") {
						
		        			Ext.Ajax.request({
		            			url:'menu!check.do',
		            			params:{
		                			iconCls:e.record.data.iconCls,
		               	 			parentID:addForm.getForm().findField("entity.id").getValue()
		            			},
		            			method:'POST',
		            			success:function(response, options) {
		            				var obj = Ext.decode(response.responseText);
									if (obj["success"]) {
										Ext.MessageBox.alert('提示 ', obj["m"]);
		                				return false;
		                				// 验证通过后提交数据
		                			} else {
										buttonSubmit(e);
		                			}
		            			},
		            			failes:function() {
		            				Ext.MessageBox.alert('提示 ', "添加按钮失败！");
		            			}
		        			});
						} else {
							buttonSubmit(e);
						}
		        	}
		    	});
    	
			}

			// 点击添加按钮时触发的事件
			function addButtonClick() {

				if (myNode == undefined) {
					Ext.MessageBox.alert('提示', '请先选择应用！');
					return false;
				}
	
				// 判断window是否存在，不存在创建window
				if (!addDicWin) {
					// 构建win中的控件
					winBuild();
					addDicWin = new Ext.Window( {
							title :'应用管理',
							width :450,
							height :550,
							closeAction :'hide',
							plain :true,
							modal :true,
							items :[addForm,gridButton],buttons:[{text:'提交',id:'btnSubmit',
			            										hidden:<%=session.getAttribute("btn_save_display")!= null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>,
			            										handler:formSubmit},
							                          {text:'关闭',id:'btnClose',handler:function(){addDicWin.hide()}}]
						});
				}
	
			    addForm.getForm().reset();
				addForm.getForm().findField("entity.parentID").setValue(myNode.id);
				storeGrid.baseParams.id = "-1";
				storeGrid.reload({params:{start:0}});
				addDicWin.show(this);
			}
		
			// 点击添加按钮时触发的事件
			function editButtonClick() {
			
				// 判断window是否存在，不存在创建window
				if (!addDicWin) {
					// 构建win中的控件
					winBuild();
					addDicWin = new Ext.Window( {
							title :'应用管理',
							width :450,
							height :550,
							closeAction :'hide',
							plain :true,
							modal :true,
							items :[addForm,gridButton],buttons:[{text:'提交',id:'btnSubmit',
																hidden:<%=session.getAttribute("btn_save_display")!= null || "1".equals(session.getAttribute("SESSION_ISADMIN")) ? false:true%>,
																handler:formSubmit},
							                          {text:'关闭',id:'btnClose',handler:function(){addDicWin.hide()}}]
						});
					}
					addDicWin.show(this);
			}
		
			// 验证数据并提交
			function formSubmit() { 
				if (addForm.form.isValid()) {
					addForm.getForm().submit({
						waitMsg :'保存数据...',
						success : function(form, action) {
							if (action.result.success) {
								Ext.MessageBox.alert('提示 ', "保存成功！");
								addDicWin.hide();
								if (myNode.id == "0") {
									tree.root.reload();
								} else if (myNode.parentNode != null) {
				           			myNode.parentNode.reload();
				           		}
							}
						},
						failure : function() {
							Ext.MessageBox.alert('提示', '保存失败！');
							addDicWin.hide();
							}
						});
				}
			};
		
			// 删除
			function delButtonClick() {
			
				if ((myNode == undefined) || (myNode == null) || (myNode.id == "0")) {
					Ext.MessageBox.alert('提示', '请您首先选择要删除的应用！');
					return false;
				}

				if (!myNode.leaf) {
					Ext.MessageBox.alert('提示','【' + myNode.text + '】有子应用不能删除。');
					return;
				}
				Ext.MessageBox.confirm('消息', '确认要删除所选应用?' ,function(btn) {
				
				if (btn == "yes") {
					Ext.Ajax.request( {
						method :'POST',
						url :'menu!delete.do',
						params : {
							id :myNode.id
						},
						success : function(response) {
							if (myNode.id =="0") {
								tree.reload();
							} else if (myNode.parentNode.childNodes.length == 1) {
								if (myNode.parentNode.parentNode != null) {
									myNode.parentNode.parentNode.reload();
								}
							} else {
			           				myNode.parentNode.reload();
			           		}
							Ext.MessageBox.alert('提示', "删除成功！");
							},
							failure : function() {
								Ext.MessageBox.alert('提示', '数据删除失败！');
							}
						});
					}
				});
			};

			// 修改
			function updateButtonClick() {
			
				if (myNode == undefined ||myNode.id == "0") {
					Ext.MessageBox.alert('提示','请您首先选择要修改的应用!');
					return;
				}
				Ext.Ajax.request({
					method :'POST',
					url :'menu!find.do',
					params : {id :myNode.id},
					success : function(response, options) { 
						if (Ext.isIE) {
							window.document.getElementById("editDicButton").click();
						} else {
							editButtonClick();
						}
						// 页面控件赋值
						var obj = Ext.decode(response.responseText);
						for (var p in obj) {
							try {
								addForm.getForm().findField("entity." + p).setValue(obj[p]);
							} catch (e){
							}
						}
						storeGrid.baseParams.id = obj["id"];
						//if (myNode.leaf == false) {
						//	storeGrid.baseParams.id = "-1";
						//}
						storeGrid.reload({params:{start:0}});
					},
					failure : function() {
						Ext.MessageBox.alert('提示 ', '提取数据失败！');
					}
				});
			}
		
			// 删除按钮
			function deleteButton(b) {
				Ext.MessageBox.confirm('消息', '确认要删除所选按钮?',function(btn) {
					if (btn!="yes") {
						return false;
					}
					Ext.Ajax.request({
						method :'POST',
						url :'menu!delete.do',
						params : {id:b},
						success : function(response) {
							storeGrid.reload({params:{start:0}});
							Ext.MessageBox.alert('提示', "按钮删除成功！");
						},
						failure : function() {
							Ext.MessageBox.alert('提示', '数据删除失败！');
						}
					});
				});
			};

	    	// 列表保存数据
	    	function buttonSubmit(e) {
	    	
				Ext.Ajax.request({
	            	url:'<%=contextPath%>/menu!saveButton.do',
	            	params:{
	                	id:e.record.data.id,
	                	iconCls:e.record.data.iconCls,
	                	title:e.record.data.title,
	                	sortId:e.record.data.sortId,
	               	 	parentID:addForm.getForm().findField("entity.id").getValue()
	            	},
	            	method:'POST',
	            	success:function(){
	                	e.record.commit(false);
	                	storeGrid.reload({params:{start:0}});
	            	}
	        	});
	    	}
		</script>
	</head>
	
</html>
